import json
import requests
from bisheng.api.jsj_api.model.fault_work_order import FaultWorkOrder, FaultWorkOrderDao
from bisheng.api.jsj_api.model.fault_work_ticket import FaultWorkTicket, FaultWorkTicketDao
from bisheng.api.jsj_api.tool_service import MetroFaultService
from bisheng.api.jsj_api.model.metro_fault import ConfigDao
from bisheng.cache.redis import redis_client
from bisheng.utils.logger import logger


message_center_url = 'http://10.21.199.174:8080/system/todoTasks/addTask'


class MessageService:

    @staticmethod
    def message_center_send(username,to_username,agency_name,message):
        flow_id = ConfigDao.get_config_by_key("flow_id").value
        print(json.dumps(message, ensure_ascii=False))
        # 准备请求数据
        payload = {
            "sourceType": "agent",
            "flowId": flow_id,
            "agencyName": agency_name,
            "sender": username,
            "recipient": to_username,
            "isHandle": 0,
            "content": json.dumps(message, ensure_ascii=False),
        }
        logger.info(f"payload:{payload}")

        # 设置请求头
        headers = {
            "Content-Type": "application/json"
        }

        try:
            url = ConfigDao.get_config_by_key("message_center_send_message").value
            # 发送POST请求
            response = requests.post(url, data=json.dumps(payload), headers=headers)

            # 检查响应状态
            response.raise_for_status()

            result = response.json()
            logger.info(f"response:{result}")

            # 检查响应内容
            if result.get("code") == 200 and result.get("msg") == "操作成功":
                logger.info(f"请求成功：{result.get('msg','')}")
                return "成功"
            else:
                return None

        except requests.exceptions.RequestException as e:
            logger.info(f"请求message_center发送消息失败: {e}")
            return None

    @staticmethod
    def get_default_message():
        pass

    def send_message_b_first(self,global_group_id,a_chat_id,fwo_id,fwt_id):
        try:
            tool_service = MetroFaultService()
            alarm_records = tool_service.get_alarm_record_by_group_id(global_group_id)
            alarm = tool_service.process_alarm_records(
                [alarm_record.dict() for alarm_record in alarm_records])
            message_str = tool_service.get_question_str_first(global_group_id,a_chat_id)
            message = {"a_chat_id": a_chat_id,"group_id":global_group_id, "description":alarm.get("description",''),
                       "order_id":fwo_id, "ticket_id":fwt_id, "message": message_str}
            print(message)
            agency_name = f"{alarm.get('station','')}  {alarm.get('equipment','')} {', '.join(alarm.get('description',''))} 位置故障"
            self.message_center_send("bdgbz","sgfzr",agency_name,message)
        except Exception as e:
            print(f"Error in send_message: {e}")

    def send_message_c_first(self,global_group_id,a_chat_id,fwo_id,fwt_id):
        try:
            tool_service = MetroFaultService()
            alarm_records = tool_service.get_alarm_record_by_group_id(global_group_id)
            alarm = tool_service.process_alarm_records(
                [alarm_record.dict() for alarm_record in alarm_records])
            message_str = tool_service.get_question_str_third(global_group_id,a_chat_id)
            message = {"a_chat_id": a_chat_id, "group_id": global_group_id, "description":alarm.get("description",''),
                       "order_id":fwo_id, "ticket_id":fwt_id, "message": message_str}
            agency_name = f"{alarm.get('station', '')}  {alarm.get('equipment', '')} {', '.join(alarm.get('description', ''))} 位置故障"
            self.message_center_send("bdgbz", "bdjsg", agency_name, message)
        except Exception as e:
            print(f"Error in send_message: {e}")

    def send_bc_message(self,global_group_id,chat_id):
        fwo_id = ""
        fwt_id = ""
        fwo = FaultWorkOrderDao.get_fault_work_order_by_group_id_chat_id(global_group_id, chat_id)
        fwt = FaultWorkTicketDao.get_fault_work_ticket_by_group_id_chat_id(global_group_id, chat_id)
        if fwo is not None:
            fwo = fwo.dict()
            fwo_id = str(fwo["id"])
        if fwt is not None:
            fwt = fwt.dict()
            fwt_id = str(fwt["id"])

        print(fwt_id,fwo_id)

        self.send_message_b_first(global_group_id,chat_id,fwo_id,fwt_id)
        self.send_message_c_first(global_group_id,chat_id,fwo_id,fwt_id)

    @staticmethod
    def get_message_list_by_redis():

        retrieved_elements = []
        while True:
            element = redis_client.lpop("message_list_key")  # 使用 lpop 从列表头部移除元素
            if element:
                retrieved_elements.append(json.loads(element.decode('utf-8')))
            else:
                break

        return retrieved_elements





